using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Xml;

namespace c3o.Framework.Web
{
    public class OpmlReader : SiteReader
    {
        public DataTable Header = null;
        public XmlNode Detail = null;

        public OpmlReader(string url)
        {
            XmlDocument xml = new XmlDocument();

            // Read rss feed into XmlDocument
            xml.LoadXml(this.ReadPage(url));

			//this.opml = new Opml(xml);

			// Load header into datatable
            this.Header = this.GetHeader(xml);

            // Load items into datatable
            this.Detail = xml.DocumentElement.ChildNodes[1];
        }


        public DataTable GetHeader(XmlDocument xml)
        {
            DataTable dt = new DataTable();

            XmlElement nodRoot = xml.DocumentElement;

            XmlNode headNode = nodRoot.ChildNodes[0];

            //XmlNodeList nodItems = nodRoot.GetElementsByTagName("head");

            // Create columns
            foreach (XmlNode childNode in headNode.ChildNodes)
            {
                if (!dt.Columns.Contains(childNode.Name))
                {
                    dt.Columns.Add(childNode.Name);

                    foreach (XmlAttribute attribute in childNode.Attributes)
                    {
                        if (!dt.Columns.Contains(childNode.Name + "_" + attribute.Name))
                        {
                            dt.Columns.Add(childNode.Name + "_" + attribute.Name);
                        }
                    }
                }
            }

            // Create row
            DataRow row = dt.NewRow();

            // Populate data into row
            foreach (XmlNode childNode in headNode.ChildNodes)
            {
                row[childNode.Name] = childNode.InnerXml;

                foreach (XmlAttribute attribute in childNode.Attributes)
                {
                    row[childNode.Name + "_" + attribute.Name] = attribute.Value;
                }
            }

            dt.Rows.Add(row);

            //	return datatable;
            return dt;
        }

    }
}